<template>
  <div>
    <a-upload
      list-type="picture-card"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :transform-file="transformFile"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < 1">
        <a-icon type="plus" />
        <div class="ant-upload-text">立即上传</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
import { getBase64 } from "@/utils/convertUtils/convert";
export default {
  props: {
    fileList: {
      type: Array,
      require: false,
    },
  },
  data() {
    return {
      previewVisible: false,
      previewImage: "",
    };
  },
  methods: {
    //#region 上传图片
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange(info) {
      // 上传数据改变时
      //   if (info.file.status === "done") {
      //     const res = info.file.response;
      //     if (res.code === 0) {
      //       this.$message.error(`图片上传成功`);
      //     } else {
      //       this.$message.error(`图片上传失败`);
      //     }
      //   } else if (info.file.status === "error") {
      //     this.$message.error(`图片上传失败`);
      //   }
      let imgList = [...info.fileList];
      // 1. 限制上传文件数量
      //只显示最近上传的1个文件，旧文件将被新文件取代
      imgList = imgList.slice(-1);
      //   2. 从响应读取并显示文件链接
      imgList = imgList.map((file) => {
        if (file.response) {
          // 组件将显示文件。url链接
          file.url = file.response.url;
        }
        return file;
      });
      this.$emit("uploadCallBack", imgList);
    },
    // 上传前对文件限制
    beforeUpload(file) {
      const format =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/bmp";
      if (!format) {
        this.$message.error("图片格式有误!");
        return;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片大小最大为2MB!");
        return;
      }
      if (isLt2M && format) {
        // this.imgList = [file];
        this.$emit("uploadCallBack", [file]);
      }
      return false;
    },
    // 上传后添加水印
    transformFile(file) {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          const canvas = document.createElement("canvas");
          const img = document.createElement("img");
          img.src = reader.result;
          img.onload = () => {
            const ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);
            ctx.fillStyle = "red";
            ctx.textBaseline = "middle";
            ctx.fillText("DuLing", 20, 20);
            canvas.toBlob(resolve);
          };
        };
      });
    },
    //#endregion
  },
};
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.avatar {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>

// 父beforeCreate->父created->父beforeMount->子beforeCreate->子created->子beforeMount->子mounted->父mounted。